package com.llyb.tingshu.account.receiver;

import com.llyb.tingshu.account.service.RechargeInfoService;
import com.llyb.tingshu.account.service.UserAccountService;
import com.llyb.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import io.micrometer.common.util.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class AccountReceiver {


    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private RechargeInfoService rechargeInfoService;

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_ACCOUNT,durable = "true",autoDelete = "false"),
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER,durable = "true",autoDelete = "false"),
            key = {MqConst.ROUTING_USER_REGISTER}
    ))
    public void rechargePaySuccess(String orderNo, Message message, Channel channel){

        try {
            if (!StringUtils.isEmpty(orderNo)) {
                rechargeInfoService.rechargePaySuccess(orderNo);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


    /**
     * 用户注册成功
     * @param userId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_USER,durable = "true",autoDelete = "false"),
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER,durable = "true",autoDelete = "false"),
            key = {MqConst.ROUTING_USER_REGISTER}
    ))
    public void register(Long userId, Message message, Channel channel){

        try {
            if (userId!=null) {
                log.info("用户注册成功，用户id：{}",userId);
                userAccountService.register(userId);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
